#include "mytcpsocket.h"


#include<QDebug>

myTcpSocket::myTcpSocket()
{
    connect(this, SIGNAL(readyRead()), this, SLOT(recvMsg()));
    connect(this, SIGNAL(disconnected()), this, SLOT(clientOffLine()));
}

QString myTcpSocket::getStrName()
{
    return m_strName;
}

void myTcpSocket::recvMsg()
{
    qDebug()<<this->bytesAvailable();
    uint uiPDULen = 0;
    this->read((char*)&uiPDULen, sizeof(uint));
    qDebug()<<uiPDULen;
    uint uiMsgLen = uiPDULen - sizeof(PDU);
    PDU *pdu = mkPDU(uiMsgLen);
    this->read((char*)pdu+sizeof(uint), uiPDULen-sizeof(uint));
    qDebug()<<pdu->uiMsgType<<(char*)(pdu->caMsg);

    switch(pdu->uiMsgType)
    {
    case ENUM_MSG_TYPE_REGIST_REQUEST:
    {
        char CaName[32] = {'\0'};
        char CaPwd[32] = {'\0'};
        memcpy(CaName, pdu->caData, 32);
        memcpy(CaPwd, pdu->caData+32, 32);
        qDebug()<<pdu->uiMsgType<<CaName<<CaPwd<<pdu->caData;
        bool ret = OpenDB::getInstance().registHandle(CaName, CaPwd);
        PDU* resPdu = mkPDU(0);
        resPdu->uiMsgType = ENUM_MSG_TYPE_REGIST_RESPOND;
        if(ret)
        {
            strcpy(resPdu->caData,REGIST_OK);
        }
        else
        {
            strcpy(resPdu->caData,REGIST_FAILED);
        }
        this->write((char*)resPdu, resPdu->uiPDULen);
        free(resPdu);
        resPdu = NULL;
        break;
    }
    case ENUM_MSG_TYPE_LOGIN_REQUEST:
    {
        char CaName[32] = {'\0'};
        char CaPwd[32] = {'\0'};
        memcpy(CaName, pdu->caData, 32);
        memcpy(CaPwd, pdu->caData+32, 32);
        qDebug()<<pdu->uiMsgType<<CaName<<CaPwd<<pdu->caData;
        bool ret = OpenDB::getInstance().loginHandle(CaName, CaPwd);
        PDU* resPdu = mkPDU(0);
        resPdu->uiMsgType = ENUM_MSG_TYPE_LOGIN_RESPOND;
        if(ret)
        {
            strcpy(resPdu->caData,LOGIN_OK);
            m_strName = CaName;
        }
        else
        {
            strcpy(resPdu->caData,LOGIN_FAILED);
        }
        this->write((char*)resPdu, resPdu->uiPDULen);
        free(resPdu);
        resPdu = NULL;


        break;
    }

    default:
        break;

    }

    free(pdu);
    pdu = NULL;


}

void myTcpSocket::clientOffLine()
{
    OpenDB::getInstance().clientOffLine(m_strName.toStdString().c_str());
    emit clientOff(this);
}
